package cz.worsik.android.test.rideshare;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Date;

import cz.worsik.android.test.rideshare.constants.EMenuItem;
import cz.worsik.android.test.rideshare.constants.ViewConst;
import cz.worsik.android.test.rideshare.db.DbAdapter;
import cz.worsik.android.test.rideshare.db.DbVersion;
import cz.worsik.android.test.rideshare.fragments.AbstractFragment;
import cz.worsik.android.test.rideshare.fragments.JizdyFragment;
import cz.worsik.android.test.rideshare.fragments.KontaktyFragment;
import cz.worsik.android.test.rideshare.fragments.NavigationDrawerFragment;
import cz.worsik.android.test.rideshare.fragments.PlatbyFragment;
import cz.worsik.android.test.rideshare.util.KalendarTools;
import cz.worsik.android.test.rideshare.view.KalendarButton;

public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private FragmentManager fragmentManager;
    private CharSequence mTitle;
    public PopupWindow popup_window;
    LinearLayout popup;
    DbAdapter db;
    LayoutInflater inflater;
    //public ViewGenerator generator;

    TextView pole_datum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // inflater
        inflater = (LayoutInflater) MainActivity.this.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        // set up database
        setUpDatabase();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    public void setUpDatabase() {

        db = new DbAdapter(this);
        db.open();
        // smazani databaze a jeji znovuvytvoreni
        int updated = db.checkVersion(false);
        switch(updated)
        {
            case DbVersion.NO_VERSION_UPDATED:
                break;
            case DbVersion.MINOR_VERSION_UPDATED:
                showToast("Aplikace provedla aktualizaci minor verze databáze. Uložená data zůstala nezměněna.", true);
                break;
            case DbVersion.MAJOR_VERSION_UPDATED:
                showToast("Aplikace provedla aktualizaci major verze databáze. Data byla vymazána.", true);
                break;
            case DbVersion.MAJOR_VERSION_NEED_UPDATE:
                showToast("Aplikace potřebuje aktualizaci major verze databáze. Pro správný chod je nutné vymazat data.", true);
                break;
        }
        if (db.getContactCount() <= 0)
        {
            //showToast(getString(R.string.msg_creating_from_template));
            //vlozDataZeSablonyDoDB();
        }
        db.close();
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        Fragment f = null;
        EMenuItem mi = EMenuItem.values()[position];
        switch (mi)
        {
            case TITLE_SPINNER:
                break;
            case SPINNER_ROUTE:
                break;
            case TITLE_MENU:
                break;
            case MENU_DRIVEWAYS:
               f = JizdyFragment.newInstance();
                break;

            case MENU_PAYMENTS:
                f = PlatbyFragment.newInstance();
                break;

            case MENU_CONTACTS:
                f = KontaktyFragment.newInstance();
                break;

            case MENU_EXIT:     // EXIT
                finish();
                break;

        }
        if (f != null)
        {
            getSupportFragmentManager().beginTransaction()
                    .replace(AbstractFragment.container, f)
                    .commit();
        }
    }

    public void onFragmentnAttached(AbstractFragment fragment) {

        mTitle = fragment.getActionBarTitle();
        restoreActionBar();
    }

    public void changeFragment(int section) {

        onNavigationDrawerItemSelected(section);
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_settings:
                showToast("Zobrazím nastavení");
                return true;
            case R.id.action_quit:
                System.exit(0);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void showToast(String text)
    {
        showToast(text, false);
    }

    public void showToast(String text, boolean dlouhy)
    {
        int delka = dlouhy ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(MainActivity.this, text, delka);

        toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
    }

    public void zHoraDolu() {
        //showToast("Down Swipe");
    }

    public void zDolaNahoru() {
        //showToast("Up Swipe");
    }

    public void pouzeClick(View v)
    {
        KalendarButton btn = (KalendarButton) v;
        int position = btn.getPosition();

        ViewConst.setDate(KalendarTools.getDateOnPosition(ViewConst.getDate(), position));

        toggleCalendar(v);
    }

    public void setDateLabel() {
        pole_datum = (TextView) findViewById(R.id.date);
        pole_datum.setText(KalendarTools.getTextForDateLabel(getApplicationContext(), ViewConst.getDate()));
    }

    public String getDateLabel() {
        pole_datum = (TextView) findViewById(R.id.date);
        return pole_datum.getText().toString();
    }

    public void toggleCalendar(View view)
    {
        TableLayout kalendar = (TableLayout) findViewById(R.id.inc_kalendar);
        if (kalendar.getVisibility() == View.GONE) {
            kalendar.setVisibility(View.VISIBLE);
            setBtnText();
        }
        else {
            kalendar.setVisibility(View.GONE);
        }
        setDateLabel();
    }

    public void prevMonth(View view)
    {
        ViewConst.prevMonth();
        setDateLabel();
        int resId = getResources().getIdentifier(ViewConst.getMesic(), "string", getPackageName());
        showToast(getString(resId)+" "+ViewConst.getRok());
        setBtnText();
    }

    public void prevDay(View view)
    {
        ViewConst.prevDay();
        setDateLabel();
        setBtnText();
    }

    public void nextDay(View view)
    {
        ViewConst.nextDay();
        setDateLabel();
        setBtnText();
    }

    public void nextMonth(View view)
    {
        ViewConst.nextMonth();
        setDateLabel();
        int resId = getResources().getIdentifier(ViewConst.getMesic(), "string", getPackageName());
        showToast(getString(resId)+" "+ViewConst.getRok());
        setBtnText();
    }

    public void today(View view)
    {
        ViewConst.today();
        setDateLabel();
        showToast(getResources().getString(R.string.info_today, getDateLabel()));
        setBtnText();
    }

    public void jizdyTabChange(View view)
    {
        Button dnes = (Button) findViewById(R.id.tab_dnes);
        Button tyden = (Button) findViewById(R.id.tab_tyden);
        Button mesic = (Button) findViewById(R.id.tab_mesic);
        Button vse = (Button) findViewById(R.id.tab_vse);

        int color_active = getResources().getColor(R.color.tab_active);
        int color_inactive = getResources().getColor(R.color.tab_inactive);

        dnes.setBackgroundColor(color_inactive);
        tyden.setBackgroundColor(color_inactive);
        mesic.setBackgroundColor(color_inactive);
        vse.setBackgroundColor(color_inactive);

        switch (view.getId())
        {
            case R.id.tab_dnes:
                // zmena barvy
                dnes.setBackgroundColor(color_active);
                break;
            case R.id.tab_tyden:
                // zmena barvy
                tyden.setBackgroundColor(color_active);
                break;
            case R.id.tab_mesic:
                // zmena barvy
                mesic.setBackgroundColor(color_active);
                break;
            case R.id.tab_vse:
                // zmena barvy
                vse.setBackgroundColor(color_active);
                break;
        }
    }

    public void platbyTabChange(View view)
    {
        Button bilance = (Button) findViewById(R.id.tab_bilance);
        Button platby = (Button) findViewById(R.id.tab_platby);

        View b_content = findViewById(R.id.inc_bilance_p);
        View p_content = findViewById(R.id.inc_platby);

        int color_active = getResources().getColor(R.color.tab_active);
        int color_inactive = getResources().getColor(R.color.tab_inactive);

        bilance.setBackgroundColor(color_inactive);
        platby.setBackgroundColor(color_inactive);

        switch (view.getId())
        {
            case R.id.tab_bilance:
                p_content.setVisibility(View.GONE);
                b_content.setVisibility(View.VISIBLE);
                // zmena barvy
                bilance.setBackgroundColor(color_active);
                break;
            case R.id.tab_platby:
                b_content.setVisibility(View.GONE);
                p_content.setVisibility(View.VISIBLE);
                // zmena barvy
                platby.setBackgroundColor(color_active);
                break;
        }
    }

    public void setBtnText()
    {
        Date datum = ViewConst.getDate();

        int position = 0;
        for (int i=1; i <= 6; i++)
        {
            for (String den: KalendarTools.dny)
            {
                String btn_id = den+"_"+i;

                int resID = getResources().getIdentifier(btn_id, "id", getPackageName());
                KalendarButton btn = (KalendarButton) findViewById(resID);

                Date position_date = KalendarTools.getDateOnPosition(datum, position);
                Integer btn_den = KalendarTools.getDayOnPosition(datum, position);
                btn.setText(btn_den.toString());

                //Log.d("CAL BTN TEXT "+position,btn.getText().toString());

                Calendar btn_cal = Calendar.getInstance();
                btn_cal.setTime(position_date);

                Calendar now_cal = Calendar.getInstance();
                now_cal.setTime(ViewConst.getNow());

                Calendar zobraz_cal = Calendar.getInstance();
                zobraz_cal.setTime(datum);

                if(btn_cal.get(Calendar.DAY_OF_MONTH) == zobraz_cal.get(Calendar.DAY_OF_MONTH)
                        && btn_cal.get(Calendar.MONTH) == zobraz_cal.get(Calendar.MONTH)
                        && btn_cal.get(Calendar.YEAR) == zobraz_cal.get(Calendar.YEAR))
                {
                    btn.setBackgroundResource(R.drawable.button_red);
                    btn.setTextColor(Color.WHITE);
                }
                else if (btn_cal.get(Calendar.DAY_OF_MONTH) == now_cal.get(Calendar.DAY_OF_MONTH)
                        && btn_cal.get(Calendar.MONTH) == now_cal.get(Calendar.MONTH)
                        && btn_cal.get(Calendar.YEAR) == now_cal.get(Calendar.YEAR))
                {
                    btn.setBackgroundResource(R.drawable.button_orange);
                    btn.setTextColor(Color.WHITE);
                }
                else if (KalendarTools.getColorOnPosition(datum, position))
                {
                    btn.setTextColor(Color.WHITE);
                    btn.setBackgroundResource(R.drawable.button_gray);
                }
                else
                {
                    btn.setTextColor(Color.GRAY);
                    btn.setBackgroundResource(R.drawable.button_gray);
                }
                btn.setPosition(position);

                position ++;
            }
        }
    }

    public void clicked(View view)
    {
        showToast("Kliknuto na tlacitko");
    }
}
